import type { message } from 'antd';

import { store } from '@/store';

/** 显示加载弹窗阈值 单位: 毫秒 */
const SHOW_LOADING_THRESHOLD = 0;
/** 显示loading阈值 */
let showLoadingTimer: ReturnType<typeof setTimeout> | null = null;
let loadingInstance: ReturnType<typeof message.loading> | null = null;

export const showLoading = (msg?: boolean | string, threshold = SHOW_LOADING_THRESHOLD): void => {
  const loading = () => {
    if (store.app) {
      loadingInstance = store.app.message.loading({
        content: typeof msg === 'string' ? msg : '请求数据中...'
      });
    }
  };

  if (threshold > 0) {
    if (showLoadingTimer) {
      clearTimeout(showLoadingTimer);
    }

    showLoadingTimer = setTimeout(() => {
      loading();
    }, threshold);
  } else {
    loading();
  }
};

export const hideLoading = () => {
  if (showLoadingTimer) {
    clearTimeout(showLoadingTimer);
  }

  loadingInstance?.();
};

export const showSuccess = (msg?: boolean | string): void => {
  store.app?.message.success({
    content: typeof msg === 'string' ? msg : '请求成功'
  });
};

export const showFail = (msg?: boolean | string): void => {
  store.app?.message.error({
    content: typeof msg === 'string' ? msg : '请求失败'
  });
};

/** 移除重复的字符串 */
export const replaceMultiText = (text: string, replaceText: string): string => {
  return text.replace(new RegExp(`(${replaceText}){1,}`, 'g'), '$1');
};
